package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.domain.Menu;
import cn.wolfcode.crm.domain.Permission;
import cn.wolfcode.crm.mapper.MenuMapper;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.service.IMenuService;
import cn.wolfcode.crm.util.PageResult;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Iterator;
import java.util.List;

@Service
public class MenuServiceImpl implements IMenuService {

    @Autowired
    private MenuMapper menuMapper;

    @Override
    public void deleteByPrimaryKey(Long id) {
        List<Menu> menus = menuMapper.selectChildById(id);
        if (menus != null){
            for (Menu menu : menus) {
                deleteByPrimaryKey(menu.getId());
            }
            menuMapper.deleteByPrimaryKey(id);
        }
        menuMapper.deleteByPrimaryKey(id);
        return;
    }

    @Override
    public Menu selectByPrimaryKey(Long id) {
        return menuMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Menu> selectAll() {
        return menuMapper.selectAll();
    }

    @Override
    public void saveOrUpdate(Menu entity) {
        if (entity.getId() != null){
            menuMapper.updateByPrimaryKey(entity);
        }else {
            menuMapper.insert(entity);
        }
    }

    @Override
    public List<Menu> selectByParentSn(String sn) {
//        Session session =SecurityUtils.getSubject().getSession();
//        List<Menu> menus = (List<Menu>) session.getAttribute("MENUS");
//        if (menus == null){
        List<Menu> menus = menuMapper.selectByParentSn(sn);
//            selectPermissionMenu(menus);
//            session.setAttribute("MENUS",menus);
//        }
        return menus;
    }

    public void selectPermissionMenu(List<Menu> menus){

        Iterator<Menu> iterator = menus.iterator();

        Subject subject = SecurityUtils.getSubject();

        while(iterator.hasNext()){
            Menu menu = iterator.next();

            Permission permission = menu.getPermission();
            if (permission != null){
                if(!subject.isPermitted(permission.getResource())){
                    iterator.remove();
                    continue;
                }
            }
            if (menu.getChildren().size() > 0){
                selectPermissionMenu(menu.getChildren());
            }

        }
    }



    @Override
    public PageResult query(QueryObject qo) {
        int total = menuMapper.query4Count(qo);
        if(total == 0 ){
            return new PageResult(0, Collections.EMPTY_LIST);
        }
        List<Menu> rows = menuMapper.query4List(qo);
        return new PageResult(total,rows);
    }

}
